
<template>
  <div class="container">
      <div class="search-box">
          <el-form  ref="retrievedFormRef" :model="retrievedForm" :rules="rules" label-position="right">
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="文件名称：" prop="enclosureName" label-width="100px">
                  <el-input v-model="retrievedForm.enclosureName" placeholder="请输入文件名称" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="创建者：" prop="creator" label-width="100px">
                  <el-input v-model="retrievedForm.creator" placeholder="请输入创建者" />
                </el-form-item>
              </el-col> <el-col :span="6">
              <el-form-item label="所属文件夹：" prop="directoryName" label-width="100px">
                <el-input v-model="retrievedForm.directoryName" placeholder="请输入所属文件夹" />
              </el-form-item>
            </el-col> <el-col :span="6">
              <el-form-item label="文件类型：" prop="enclosureType" label-width="100px">
                <el-select v-model="retrievedForm.enclosureType" placeholder="请选择">
                  <el-option
                    v-for="item in fileTypes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label"
                  />
                </el-select>
              </el-form-item>
            </el-col>
              <el-col :span="6">
                <el-form-item label="文件版本：" prop="enclosureVersion" label-width="100px">
                  <el-input v-model="retrievedForm.enclosureVersion" placeholder="请输入文件版本" />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="创建时间：" prop="createTime" label-width="100px">
                  <div class="demo-range">
                    <el-date-picker
                      v-model="retrievedForm.createTime"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      :default-time="defaultTime"
                      type="daterange"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :popper-options="popOptions"
                    />
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="删除时间：" prop="deleteTime" label-width="100px">
                  <div class="demo-range">
                    <el-date-picker
                      v-model="retrievedForm.deleteTime"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      :default-time="defaultTime"
                      type="daterange"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :popper-options="popOptions"
                    />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div style="justify-content: flex-end;display: flex">

              <el-button @click="searchReset">清空</el-button>
              <el-button
                  type="primary"
                  @click="searchChange"
              >查询</el-button>
          </div>
      </div>
      <layout-card
          v-model="search"
          :filters="isExampleOptions"
          headline="数据列表"
          :hasButton="false"
      >
          <template #action>
              <el-button
                  type="primary"
                  @click="setDeletionTime"
              >设置</el-button>
              <el-button
                  type="primary"
                  @click="restoreFiles(row,1)"
                  :disabled="showRestoreBtn"
              >恢复</el-button>
            <el-popconfirm title="是否清空?"  @confirm="() =>restoreFiles(row,2)">
              <template #reference>
                <el-button
                  type="danger"
                  plain
                >清空回收站</el-button>
              </template>
            </el-popconfirm>

          </template>
          <table-common
              :loading="loading"
              :columns="exampleColumns"
              :pagination="pager"
              :table-data="tabeData"
              size="small"
              @sort-change="sortChange"
              @current-change="myChangeCurrent"
              @size-change="myChangePageSize"
              @selection-change="selectionChangeHandle"
              stripe
              :height="'420px'"
          >
              <template #action="{ row }">
                <el-popconfirm title="是否恢复?"  @confirm="() =>restoreFiles(row,4)">
                  <template #reference>
                    <el-button
                      link
                      type="primary"
                    >恢复</el-button>
                  </template>
                </el-popconfirm>
                <el-popconfirm title="是否删除?"  @confirm="() =>restoreFiles(row,3)">
                  <template #reference>
                    <el-button
                      class="link-btn"
                      link
                      type="primary"
                    >删除</el-button>
                  </template>
                </el-popconfirm>

              </template>
          </table-common>
      </layout-card>
      <!-- 设置弹窗 -->
      <edit-dialog
        class="maintenance"
        :centerDialogVisible="centerDialogPreviewVisible"
        tilte="设置储存时间"
        :key="timer"
        align-center
        :defaultButton="false"
        :width="500"
        @cancel="handleCancel"
      >
          <template #content>
              <!-- <span style="margin-bottom: 20px;display: block;">设置默认时间：</span> -->
              <div class="mb-2 flex items-center text-sm">
                  <el-radio-group v-model="radio1" class="ml-4" @change="radioChanges" style="margin-left: 2rem;">
                      <el-radio label="0" size="large" style="width: 100%;">默认
                          <span style="color: #ababab;font-size:0.65rem;margin-left: 1.5rem;">(系统默认储存1个月)</span>
                      </el-radio>
                      <div style="display: flex;align-items: center;">
                          <el-radio label="1" size="large">自定义</el-radio>
                          <el-input
                              v-model="inputDuration"
                              size="small"
                              class="inputText"
                              :style="showInput"
                              @input="limitationInput"
                              style="margin-right:1rem;"
                          >
                              <template #append>
                                  <el-select v-model="selectDateType" @change="limitationInput" style="width: 50px">
                                      <el-option label="天" value="0"></el-option>
                                      <el-option label="月" value="1"></el-option>
                                  </el-select>
                              </template>
                          </el-input>
                          <span style="color: #ababab;font-size:0.65rem;">(系统最大储存3个月)</span>
                      </div>
                  </el-radio-group>
              </div>
          </template>
          <template #custom>
              <span class="dialog-footer">
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" :loading="saveBtn" @click="handleTransferSubmit">确定</el-button>
                  </span>
          </template>
      </edit-dialog>
      <!--  恢复 清空回收站 删除弹窗  -->
      <edit-dialog
        :centerDialogVisible="centerDialogTips"
        tilte="提示"
        :key="timer"
        :width="500"
        align-center
        :defaultButton="false"
        @cancel="handleCancel"
    >
        <template #content>
            <span style="font-size: 0.95rem;">{{tipsContent}}</span>
        </template>
        <template #custom>
          <span class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" :loading="saveBtn" @click="tipsTransferSubmit">确定</el-button>
              </span>
        </template>
    </edit-dialog>
  </div>
</template>
<script setup lang="ts">
  // 需要导入watch监听
  import { computed, ref, onBeforeMount, nextTick, watch, reactive, onMounted } from 'vue'
  // 以下两项需要导入
  import LayoutCard from '@/components/LayoutCard/index.vue'
  import TableCommon from '@/components/TableCommon/index.vue'
  import FilterBar from '@/components/FilterBar/index.vue'
  import {ElTree, ElMessage, FormInstance} from 'element-plus'
  import { Download, Search } from '@element-plus/icons-vue'
  import {recyclePageList, setStorageTime, restoreFilesInterface, deleteRecycleFiles, emptyRecycleBin, getRecycleSettings} from '@/api/knowledge/recycle'
  import VueOfficeExcel from '@vue-office/excel'
  import '@vue-office/excel/lib/index.css'
  import {useStore} from "vuex";
  import {eventRulesTemplateDownload} from "@/api/eventManage/eventRules";
  import {exampleColumns} from "./config/columns"
  import {getResource} from "@/api/resource"
  import editDialog from '@/components/editDialog/index.vue'
  const search = ref<FilterDataType>({});
  const retrievedForm = ref({
      enclosureName: undefined, // 文件名称 nameOrCode
      createTime: [], // 创建时间 createTimeBegin  createTimeEnd
      creator: undefined, // 创建者 createUserName
      deleteTime:[], // 删除时间 deleteTimeBegin  deleteTimeEnd
      directoryName: undefined, // 所属文件夹 dirName
      enclosureType: undefined, // 文件类型 fileType
      enclosureVersion: undefined, // 文件版本
  });
  const pager = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    pageCount: 0,
  });
  const defaultTime = [new Date(2000, 2, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)];//选择日期后的默认时间
  const popOptions = { // 日期弹窗位置
   modifiers: [
        {
            name: 'flip',
            options: {
                fallbackPlacements: ['bottom'],
                allowedAutoPlacements: ['bottom'],
            }
        }
    ]
}
  const radio1 = ref(0); // 存储类型
  const inputDuration = ref(); // 自定义设置天数值
  const selectDateType = ref(); // 自定义设置类型
  const loading=ref(false);
  // 单选按钮
  const radioValue = ref('');
  // 设置弹窗是否打开
  const centerDialogPreviewVisible = ref(false);
  const tipsContent = ref("");
  // 提示弹窗
  const centerDialogTips = ref(false);
  // 时间戳，用于确保弹窗页面能加载不同的界面
  const timer = ref();
  // 请求用户的权限树
  const { getters } = useStore();
  // 拿到vuex里面用户的信息
  // const organTree = computed(() => getters['user/getOrganTree'])
  const users = computed(() => getters['user/getUserInfo']);
  //表格数据
  const tabeData = ref([]);
  // 获取文件类型字典内容
  const fileTypes=ref([]);
  const onGetResource= async () => {
      const res = await getResource("enclosure_type");
      if(res?.code=='1'){
          fileTypes.value=res.data.properties.meta
      };
  };

  const saveBtn = ref(false);
  const showRestoreBtn = ref(true);

  /**
   * 设置
   */
  const showInput = ref("");
  const setDeletionTime = () => {
      // 调取回显设置
      getRecycleSettingsFn();
  };

    // 获取回显设置
    const getRecycleSettingsFn = async() => {
        const userId = userInfo.value.userId;
        const res = await getRecycleSettings(userId);
        if (res?.code == '1') {
          if(res.data!=null){
            radio1.value = String(res.data.configType);
            inputDuration.value = res.data.timeLong;
            selectDateType.value = String(res.data.timeType);
          }else{
            radio1.value='0'
          }

        }
        radioChanges();
        centerDialogPreviewVisible.value = true;
    }

  const radioChanges = () => {
      radio1.value == '0' ? showInput.value = 'display:none' : showInput.value = '';
  };

  const limitationInput = () => {
      if (selectDateType.value == 0) {
        // 选择为天
          if (inputDuration.value > 90) {
              inputDuration.value = 90;
          } else if (inputDuration.value < 0) {
              inputDuration.value = 0;
          }
      } else if (selectDateType.value == 1){
        // 选择为月
          if (inputDuration.value > 3) {
              inputDuration.value = 3;
          } else if (inputDuration.value < 0) {
              inputDuration.value = 0;
          }
      }
  };

  const restoreFiles = (row: any, num: number) => {
      tipsType.value = num;
      tipsData.value = row;
      if (num == 1){
          tipsContent.value = "确定要恢复勾选文件吗？";
      } else if(num == 2){
          tipsContent.value = "确定要清空回收站吗？"
      } else if(num == 3){
          tipsContent.value = "确定要删除该文件吗？"
      } else if (num == 4) {
          tipsContent.value = "确定要恢复该文件吗？";
      }
      //centerDialogTips.value = true;
    tipsTransferSubmit()
  };

  /**
   * 提示框确认按钮
   */
  const tipsType = ref();
  const tipsData = ref();
  const tipsTransferSubmit = () => {
      if (tipsType.value == 1) {
          restoreFilesInterfaceFn(tipsData.value,1);
      } else if (tipsType.value == 4) {
          restoreFilesInterfaceFn(tipsData.value,4);
      } else if (tipsType.value ==3) {
          deleteFiles();
      } else if (tipsType.value ==2) {
          emptyRecycleBinFn();
      }
  };

  // 清空回收站
  const emptyRecycleBinFn = async () => {
      saveBtn.value = true;
      const userId = userInfo.value.userId;
      const res = await emptyRecycleBin(userId);
      if (res?.code=='1') {
          ElMessage.success('清空回收站成功');
          centerDialogTips.value = false;
          saveBtn.value = false;
          getData();
      } else {
          ElMessage.error('删除文件失败');
          centerDialogTips.value = false;
          saveBtn.value = false;
      }
  };

  // 删除单个文件
  const deleteFiles = async () => {
      saveBtn.value = true;
      const res = await deleteRecycleFiles(tipsData.value.id);
      if (res?.code == '1') {
          ElMessage.success('删除文件成功');
          centerDialogTips.value = false;
          saveBtn.value = false;
          getData();
      } else {
          ElMessage.error('删除文件失败');
          centerDialogTips.value = false;
          saveBtn.value = false;
      }
  };

  // 恢复文件
  const restoreFilesInterfaceFn = (datas:any,types:any) => {
      // console.log(datas);
      const idList = ref([]);
      if (types == 1) {
          dataListSelections.value.forEach((item:any)=>{
              idList.value.push(item.id);
          });
          restFilesFn(idList.value);
      } else if (types == 4) {
          idList.value.push(datas.id);
          restFilesFn(idList.value)
      }
  };

  const restFilesFn = async (idList:any)=> {
      saveBtn.value = true;
      const res = await restoreFilesInterface(idList);
      if (res?.code=='1') {
          ElMessage.success('恢复文件成功');
          saveBtn.value = false;
          centerDialogTips.value = false;
          getData();
      } else {
          ElMessage.error('恢复文件失败');
          saveBtn.value = false;
          centerDialogTips.value = false;
      }
  };

  /**
   * 取消按钮
   */
  const handleCancel = () => {
      radio1.value = '0'; // 配置类型
      inputDuration.value = ''; // 清理时长
      selectDateType.value = '0'; // 时间类型
      centerDialogPreviewVisible.value = false;
      centerDialogTips.value = false;
  };

  /**
   * 设置弹窗确认按钮
   */
  const store = useStore();
  const userInfo = computed(() => store.state.user.userInfo);
  const handleTransferSubmit = () => {
      if (radio1.value == '1') {
          if (inputDuration.value == '' || inputDuration.value == '0') {
              ElMessage.error('请输入储存时长');
          } else {
              setStorageTimeFn();
          }
      } else if (radio1.value == '0'){
          setStorageTimeFn();
      }
  };

  /**
   * 设置存储时长
   */
  const setStorageTimeFn = async () => {
      saveBtn.value = true;
      const recycleSettings = {
          configType:parseInt(radio1.value),
          timeLong:parseInt(inputDuration.value),
          timeType:parseInt(selectDateType.value),
          user:{
              id: userInfo.value.userId,
              name: userInfo.value.name,
              organId: userInfo.value.organId || '',
              organName: userInfo.value.organName || '',
              phone: userInfo.value.phone || '',
          }
      };
      const res = await setStorageTime(recycleSettings);
      if (res?.code == '1') {
          ElMessage.success('设置成功');
          centerDialogPreviewVisible.value = false;
          saveBtn.value = false;
          handleCancel();
          getData();
      } else {
          ElMessage.error('设置失败');
          centerDialogPreviewVisible.value = false;
          saveBtn.value = false;
          handleCancel();
      }
  };

  // 获取当前选择数据
  const dataListSelections = <any>([]);
  const selectionChangeHandle = (val:any) => {
      dataListSelections.value = val;
      dataListSelections.value.length == 0 ? showRestoreBtn.value = true : showRestoreBtn.value = false;
  };

  /**
   * 清空
   */
  interface OrderItem {
      column?: string
      method?: string
  }
  const order = ref([{"column": "delete_time","method": "desc"}] as OrderItem[]);
  const searchReset = (data: any) => {
      retrievedForm.value = {
          enclosureName: undefined, // 文件名称 nameOrCode
          createTime: [], // 创建时间 createTimeBegin  createTimeEnd
          creator: undefined, // 创建者 createUserName
          deleteTime:[], // 删除时间 deleteTimeBegin  deleteTimeEnd
          directoryName: undefined, // 所属文件夹 dirName
          enclosureType: undefined, // 文件类型 fileType
          enclosureVersion: undefined, // 文件版本
      };
      order.value = [{"column": "delete_time","method": "desc"}];// 清空排序？？？
      pager.currentPage = 1;
      pager.pageSize = 10;
      getData();
  };

  /**
   * 点击查询
   */
  const searchChange = (data: any) => {
      // 这里也应该查第一页
      pager.currentPage = 1;
      getData();
  };

  //获取分页查询入参
  const getParams = () => {
    const payload = {
      pageNum: pager.currentPage,
      pageSize: pager.pageSize,
      condition:{
          nameOrCode: retrievedForm.value.enclosureName,
          createTimeBegin: retrievedForm.value.createTime[0],
          createTimeEnd: retrievedForm.value.createTime[1],
          createUserName: retrievedForm.value.creator,
          deleteTimeBegin: retrievedForm.value.deleteTime[0],
          deleteTimeEnd: retrievedForm.value.deleteTime[1],
          dirName: retrievedForm.value.directoryName,
          fileType: retrievedForm.value.enclosureType,
          enclosureVersion: retrievedForm.value.enclosureVersion,
          order:order.value
      }
    };
      return payload
  };
  // 获取数据
  const getData = async () => {
      loading.value = true;
      const payload = getParams();
      payload.condition.userId=users.value.userId; // 操作用户id
      //获取表格数据
      const res = await recyclePageList(payload);
      if(res?.code=='1'){
          tabeData.value = res.data.list;
          pager.total = res.data.total;
          pager.pageCount =
              Math.ceil(pager.total / pager.pageSize) === 0
                  ? 1
                  : Math.ceil(pager.total / pager.pageSize);
      }
      loading.value=false
  };

  /**
   * 功能-点击排序
   * @param value 排序规则
   */
  const sortChange = (data:any) => {
      pager.currentPage = 1;
      const method = data.order=='descending'?'desc':'asc';
      order.value=[{ column: data.prop=='enclosureType'?'enclosure_type':data.prop=='deleteTime'?'delete_time':data.prop, method, }];
      getData()
  };
  // pageSize改变时触发
  const myChangePageSize = (data: FilterDataType) => {
     // 感觉这里要查第一页？？？？？
     pager.currentPage = 1;
     pager.pageSize = data;
     order.value = [];// 清空排序？？？
    getData()
  };
  // current-page改变时触发
  const myChangeCurrent = (value) => {
    // 感觉这里要查第一页？？？？？
    pager.currentPage = value
    getData()
  };
  // 重置查询条件
  const resetGetData = (data: FilterDataType) => {
    search.value = data;
    getData()
  };
  onBeforeMount(async () => {
      onGetResource();
      getData();
  })
</script>
<style lang="less" scoped>
    .container {
        background: #f5f7f9;
        min-height: 100%;
        overflow: hidden;

        .inputText {
            width: 100px;
        }

        .search-box {
            background-color: #ffffff;
            padding: 20px 20px 10px 20px;
            margin: 13px 13px 0 13px;
            border-radius: 10px;
        }

        .companyTree {
            padding: 24px;
            margin: 12px 0 24px 0;
            background: #fff;
            border-radius: 8px;

            .title {
                font-size: 16px;
                font-family: HarmonyOS_Sans_SC_Medium;
                border-left: #2f7df1 2px solid;
                text-indent: 1em;
                color: #353a42;
                line-height: 16px;
                margin: 10px 0;
                display: flex;
                justify-content: space-between;
            }

            .search {
                margin-bottom: 20px;
            }

            /deep/ .el-tree-node__content {
                height: 32px;

            }

            /deep/ .el-tree-node:focus>.el-tree-node__content {
                background-color: #5daaf0; //背景色
            }

            .custom-tree-node {
                flex: 1;
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-size: 14px;
                padding-right: 8px;
                width: 100%;
                // background-color: yellow;

                .custom-tree-node-left {
                    max-width: 300px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;

                    .custom-tree-node-left-label {
                        width: 100%;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }
                }

                .oper {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    user-select: none;
                    padding-right: 0px;
                    width: 100px;

                    img {
                        width: 20px;
                        height: 20px;
                        object-fit: contain;

                        &:hover {
                            transform: scale(1.1);
                        }
                    }

                    img+img {
                        margin-left: 8px;
                    }

                    .border {
                        border-radius: 4px;
                        border: 1px solid #2f7df1;
                        padding: 2px;
                        box-sizing: border-box;
                        margin-left: 8px;
                    }
                }
            }
        }
}

.el-input__icon {
  margin: 0 5px;
}

.el-input__icon:hover {
  cursor: pointer;
}

.elRadio {
  display: flex;
  flex-direction: column;
  align-items: start;
  padding-left: 20px;
}

.daoru {
  display: flex;
  justify-content: center;
}</style>
